import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes, CategoryItem, TopCategoryItem, SubCategory } from '@/types/data'
import { topCategory } from './../constants'
// 思路: 将 数组 (字符串) - 数组 (对象) - {name: 字符串}
const defaultCategory = topCategory.map(item => {
  return {
    name: item
  }
})
// [{name: '居家'}, {name: '美食'}, {},... ]
// console.log(defaultCategory);


const useCateGoryStore = defineStore('category', {
  state() {
    return {
      // 头部分类列表
      list: defaultCategory as CategoryItem[],
      // 一级分类面包屑  
      topBreadCategory: {}  as TopCategoryItem,
      // 二级分类面包屑
      subBreadCategory: {}  as SubCategory 
    }
  },
  actions: {
    // 获取头部分类
    async getAllCategory() {
      const res = await request.get<ApiRes<CategoryItem[]>>('/home/category/head')
      // 每一个一级分类添加一个open属性, 用来控制显示隐藏
      res.data.result.forEach(item => {
        item.open = false
      })
      this.list = res.data.result
    },
    // 分类弹层 - 显示
    show(id: string){
      const category = this.list.find(item => item.id === id)
      // 非空断言
      category!.open = true
    },
    // 分类弹层 - 隐藏
    hide(id: string) {
      const category = this.list.find(item => item.id === id)
      // 非空断言
      category!.open = false
    },
    // 一级类目
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategoryItem>>('/category', {
        params: {
          id
        }
      })
      this.topBreadCategory = res.data.result
      console.log('------this.topBreadCategory---', this.topBreadCategory);
      
    },
    // 二级类目 
    async getSubFilter(id: string) {
      const res = await request.get<ApiRes<SubCategory>>('/category/sub/filter', {
        params: {
          id
        }
      })
      console.log(res);
      this.subBreadCategory = res.data.result  
    }
  }
})

export default useCateGoryStore